<template>
  <span>
    <!-- 计数器 -->
    <el-form-item v-if="isShow && itemInfo.htmlType=='inputNumber'"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-input-number v-model="itemInfo.fieldData" @change="ItemValChange"/>
    </el-form-item>
    <!-- 开关 -->
    <el-form-item v-else-if="isShow && itemInfo.htmlType=='switch'"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-switch  v-model="itemInfo.fieldData" @change="ItemValChange"/>
    </el-form-item>
    <!--整数类型-->
    <el-form-item v-else-if="isShow && itemInfo.htmlType=='number'"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-input v-model.number.trim="itemInfo.fieldData" type="number" @change="ItemValChange"/>
    </el-form-item>
    <!--小数类型-->
    <el-form-item v-else-if="isShow && (itemInfo.htmlType=='decimals' || itemInfo.htmlType=='decimals2')"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-input v-model.trim="itemInfo.fieldData"
                @keyup.native="itemInfo.fieldData=oninput(itemInfo.fieldData,itemInfo.htmlType)"
                @change="itemInfo.fieldData=oninput(itemInfo.fieldData,itemInfo.htmlType)"/>
    </el-form-item>
    <!--下拉框-->
    <el-form-item v-else-if="isShow && (itemInfo.htmlType=='select' || itemInfo.htmlType=='radio')"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-select  v-model="itemInfo.fieldData" filterable clearable @change="ItemValChange">
        <el-option v-for="(dict,index) in dictList" :key="index" :label="dict.dictLabel" :value="dict.dictValue"
                   :disabled="2==dict.status"/>
      </el-select>
    </el-form-item>
    <!--多选下拉框-->
    <el-form-item v-else-if="isShow && (itemInfo.htmlType=='multipleSelect' || itemInfo.htmlType=='checkbox')"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-select  multiple v-model="multipleSelectFieldData" filterable clearable @change="ItemValChange" :collapse-tags="true">
        <el-option v-for="(dict,index) in dictList" :key="index" :label="dict.dictLabel" :value="dict.dictValue"/>
      </el-select>
    </el-form-item>
<!--    &lt;!&ndash;复选框&ndash;&gt;-->
<!--    <el-form-item v-else-if="isShow && itemInfo.htmlType=='checkbox'  && false"-->
<!--                  class="unfixed"-->
<!--                  :label="itemInfo.columnComment"-->
<!--                  :prop="'fieldInfo.'+index+'.fieldData'"-->
<!--                  :rules="itemRule">-->
<!--      <el-checkbox-group  v-model="checkobxFieldData" @change="ItemValChange">-->
<!--        <el-checkbox v-for="(dict,index) in dictList" :label="String(dict.dictValue)" :key="index">{{dict.dictLabel}}</el-checkbox>-->
<!--      </el-checkbox-group>-->
<!--    </el-form-item>-->
<!--    &lt;!&ndash;单选框&ndash;&gt;-->
<!--    <el-form-item v-else-if="isShow && itemInfo.htmlType=='radio' && false"-->
<!--                  class="unfixed"-->
<!--                  :label="itemInfo.columnComment"-->
<!--                  :prop="'fieldInfo.'+index+'.fieldData'"-->
<!--                  :rules="itemRule">-->
<!--      <el-radio v-for="(dict,index) in dictList" v-model="itemInfo.fieldData" :key="index" @change="ItemValChange"-->
<!--                :label="dict.dictValue">{{dict.dictLabel}}</el-radio>-->
<!--    </el-form-item>-->
    <!--日期选择-->
    <el-form-item v-else-if="isShow && itemInfo.htmlType=='date'"
                  class="unfixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-date-picker clearable size="small"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd" v-model="itemInfo.fieldData" type="daterange" range-separator="-"
                      start-placeholder="开始日期" end-placeholder="结束日期"
                      @change="ItemValChange"></el-date-picker>
    </el-form-item>
    <!--时间选择-->
    <el-form-item v-else-if="isShow && itemInfo.htmlType=='datetime'"
                  class="unfixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-date-picker clearable size="small"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss" v-model="itemInfo.fieldData" type="datetimerange" range-separator="-"
                      start-placeholder="开始日期" end-placeholder="结束日期"
                      @change="ItemValChange" :default-time="['00:00:00','23:59:59']"></el-date-picker>
    </el-form-item>
    <!--地区级联选择-->
    <el-form-item v-else-if="isShow && itemInfo.htmlType=='CascaderArea'"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-cascader clearable filterable size="medium"
                    v-model="itemInfo.fieldData"
                    :options="regionData"
                    :props="cascaderProps"
                    @change="ItemValChange" />
    </el-form-item>
    <!--除以上控件外，其他类型都以输入框展示 -->
    <el-form-item v-else-if="isShow"
                  class="fixed"
                  :label="itemInfo.columnComment"
                  :prop="'fieldInfo.'+index+'.fieldData'"
                  :rules="itemRule">
      <el-input v-model="itemInfo.fieldData"  v-bind="attributes" @change="ItemValChange"/>
    </el-form-item>
  </span>
</template>

<script>
/** 引入中国全省市区的数据 **/
import {
  regionData
} from "element-china-area-data";
export default {
  name: 'FormItem',
  props: {
    index: {
      type: Number,
      default: 1
    },
    itemType: {
      type: String,
      default: 'edit'
    },
    inline: {
      type: Boolean,
      default: false
    },
    itemInfo: {
      type: Object,
      default: {}
    },
    disableStatus: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    //对象中下拉框
    selectionOptions: {
      type: Object,
      default: ()=>{},
    }
  },
  data() {
    return {
      isFullItem: false,
      dictList: [],
      selectionComponts: ['select','multipleSelect','radio','checkbox'],
      regionData:regionData,
      cascaderProps:{
        value: "value",
        label: "label",
        children: "children"
      }
    }
  },
  created() {
  },
  methods: {
    openSearch(model){
      let searchModel = {
        model: model,
        isOpenSearch: true
      }
      this.$emit('OpenSearchModel', searchModel)
    },
    ItemValChange(val) {
      if (this.itemType == 'query' && (this.itemInfo.htmlType == 'datetime' || this.itemInfo.htmlType == 'date')) {
        /** 仅CRUD查询区域中日期组件数据特殊处理 **/
        if (!this.isNotEmpty(this.itemInfo.fieldData)) {
          let dateObj = {
            key: this.itemInfo.columnName,
            type: 'timeParams',
            val: null
          }
          this.$emit('ItemValChange', dateObj, this.itemInfo)
          return
        }
        if (this.isNotEmpty(this.itemInfo.columnName) && val) {
          let dateObj = {
            key: this.itemInfo.columnName,
            type: 'timeParams',
            val: val[0] + ' TO '+ val[1]
          }
          this.$emit('ItemValChange', dateObj, this.itemInfo)
        }
      } else {
        if (val instanceof Array) {
          val = val.filter(Boolean).join(",")
        }
        if (this.itemInfo.htmlType == 'number') {
          val = Number(val)
        }
        let data = {
          key: this.itemInfo.columnName,
          val: val
        }
        this.$emit('ItemValChange', data, this.itemInfo)
      }
    },
    oninput(num, htmlType) {
      var str = num + ""
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      var lenLast = str.substr(str.length - 1)
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      //第一位不能是.
      if (len1 == ".") {
        str = ""
      }
      //最后一位不能是.
      if (str.length == 8 && lenLast == ".") {
        str = ""
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      // //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (htmlType == 'decimals2') {
        str = str.substr(0, str.indexOf('.') + 3)// 小数点后只能输两位
      }
      this.ItemValChange(str)
      return str
    }
  },
  computed: {
    // 判断是否显示
    isShow() {
      if (this.itemType == 'edit' || this.itemType == 'add') {
        return this.itemInfo.isInsert == '1'
      } else if (this.itemType == 'query') {
        return this.itemInfo.isQuery == '1'
      } else {
        return false
      }
    },
    attributes(){
      //属性对象
      let attrs={
        'type':'text'
      }
      // 多行文本框
      // if(this.itemInfo.htmlType=='textarea'){
      //   attrs['type']='textarea'
      //   attrs['autosize']={ minRows: 2, maxRows: 6}
      // }
      attrs['maxlength']=this.itemInfo.columnLength
      return attrs;
    },
    // 返回校验规则
    itemRule() {
      let rule = []
      rule.push({
        required: this.isRequired,
        message: this.itemInfo.columnComment + '不能为空',
        trigger: 'blur'
      })
      if (this.itemInfo.htmlType == 'number') {
        rule.push({
          type: 'number',
          message: this.itemInfo.columnComment + '只能为数字'
        })
      }
      return rule;
    },
    compClass() {
      let className = "";
      if (this.inline == false) {
        className = (this.itemType == 'edit' || this.itemType == 'add') ? (this.isFullItem ? 'full-item' : 'half-item') : ''
      } else {
        className = this.isFullItem ? 'full-item' : ''
      }
      return className;
    },
    // 多选下拉框
    multipleSelectFieldData: {
      get: function () {
        if (this.isNotEmpty(this.itemInfo.fieldData)) {
          return this.itemInfo.fieldData.split(',')
        } else {
          this.$set(this.itemInfo, 'fieldData', '')
          return this.itemInfo.fieldData;
        }
      },
      set: function (newValue) {
        let key = ''
        if(newValue instanceof Array){
          newValue.forEach(item => {
            key += item + ','
          })
          if (key.trim().length > 0) {
            key = key.substring(0, key.lastIndexOf(','))
          }
        }
        this.itemInfo.fieldData = key
      }
    },
    // 复选框
    checkobxFieldData: {
      get: function () {
        if (this.isNotEmpty(this.itemInfo.fieldData)) {
          return this.itemInfo.fieldData.split(',')
        } else {
          return [];
        }
      },
      set: function (newValue) {
        let key = ''
        if(newValue && newValue instanceof Array){
          key = newValue.filter(Boolean).join(",")
        }
        this.$set(this.itemInfo,'fieldData',key)
      }
    }
  },
  watch: {
    itemInfo: {
      immediate: true,
      deep:true,
      handler(nowData) {
        if (nowData.htmlType == 'textarea') {
          this.isFullItem = true
        }
        /**
         * 收集选择组件选项值信息
         */
        if (this.selectionComponts.includes(nowData.htmlType) && nowData.dictItems && Array.isArray(nowData.dictItems)) {
          this.dictList = nowData.dictItems
          if(this.isEmpty(this.selectionOptions) || !Array.isArray(this.selectionOptions[nowData.columnName])){
            this.$emit("recordSelectionOptions",nowData.columnName,nowData.dictItems)
          }
        }
        this.$emit("recordFormColumnType",nowData.columnName,nowData.htmlType)
        this.$emit("recordFormColumnName",nowData.columnName,nowData.columnComment)
      }
    }
  }
}
</script>

<style scoped>
.edit .el-form-item__content .el-input {
  /*width: calc(50%) !important;*/
  min-width: 300px;
  max-width: 500px;
}

.query > .el-form-item__content {
  margin-left: 0px !important;
}
</style>
